package com.amazon.shop.utils;

import com.amazon.shop.spapi.client.ApiException;
import com.amazon.shop.vo.ProductUploadVo;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 生成xml文件工具类
 *
 * @Author 郭非
 * @Date 2021/6/12
 * @Time 8:36
 * @Version 1.0
 */
public class XMLUtils {
    /**
     * 生成xml文件
     *
     * @throws ParserConfigurationException
     * @throws TransformerException
     */
    public static File createXML(List<ProductUploadVo> productVoList) throws ParserConfigurationException, TransformerException, ApiException {
        int i = 0;
        File file = new File("F:\\xml\\product.xml");
        for (ProductUploadVo productUploadVo : productVoList) {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = null;
            try {
                documentBuilder = factory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
            Document document = documentBuilder.newDocument();
            // 不显示standalone="no"
            document.setXmlStandalone(true);
            Element amazonEnvelope = document.createElement("AmazonEnvelope");
            document.appendChild(amazonEnvelope);
            amazonEnvelope.setAttribute("xsi:noNamespaceSchemaLocation", "amzn-envelope.xsd");
            amazonEnvelope.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

            Element header = document.createElement("Header");
            amazonEnvelope.appendChild(header);
            Element documentVersion = document.createElement("DocumentVersion");
            documentVersion.setTextContent("1.01");
            Element merchantIdentifier = document.createElement("MerchantIdentifier");
            merchantIdentifier.setTextContent("ListingsContentHandler");
            header.appendChild(documentVersion);
            header.appendChild(merchantIdentifier);

            Element messageType = document.createElement("MessageType");
            messageType.setTextContent("Product");
            amazonEnvelope.appendChild(messageType);

            Element purgeAndReplace = document.createElement("PurgeAndReplace");
            amazonEnvelope.appendChild(purgeAndReplace);
            purgeAndReplace.setTextContent("false");

            Element message = document.createElement("Message");
            amazonEnvelope.appendChild(message);

            //设置产品编号
            Element messageID = document.createElement("MessageID");
            message.appendChild(messageID);

            String messageId = productUploadVo.getMessageId();
            if (!StringUtils.isEmpty(messageId)) {
                messageID.setTextContent(messageId);
            }

            Element operationType = document.createElement("OperationType");
            message.appendChild(operationType);
            String voOperationType = productUploadVo.getOperationType();
            operationType.setTextContent(voOperationType);

            Element product = document.createElement("Product");
            message.appendChild(product);

            //设置产品sku
            String voSku = productUploadVo.getSku();
            if (!StringUtils.isEmpty(voSku)) {
                Element sku = document.createElement("SKU");
                product.appendChild(sku);
                sku.setTextContent(voSku);
            }

            Element standardProductID = document.createElement("StandardProductID");
            product.appendChild(standardProductID);

            String voType = productUploadVo.getType();
            if (!StringUtils.isEmpty(voType)) {
                Element element = document.createElement("Type");
                standardProductID.appendChild(element);
                element.setTextContent(voType);
            }

            String value1 = productUploadVo.getValue();
            if (!StringUtils.isEmpty(value1)) {
                Element value = document.createElement("Value");
                standardProductID.appendChild(value);
                value.setTextContent(value1);
            }

            Element condition = document.createElement("Condition");
            product.appendChild(condition);

            String conditionType1 = productUploadVo.getConditionType();
            if (!StringUtils.isEmpty(conditionType1)) {
                Element conditionType = document.createElement("ConditionType");
                condition.appendChild(conditionType);
                conditionType.setTextContent(conditionType1);
            }

            Element descriptionData = document.createElement("DescriptionData");
            product.appendChild(descriptionData);

            //设置产品标题
            String voTitle = productUploadVo.getTitle();
            if (!StringUtils.isEmpty(voTitle)) {
                Element title = document.createElement("Title");
                descriptionData.appendChild(title);
                title.setTextContent(voTitle);
            }

            //设置产品品牌
            String productVoBrand = productUploadVo.getBrand();
            if (!StringUtils.isEmpty(productVoBrand)) {
                Element brand = document.createElement("Brand");
                descriptionData.appendChild(brand);
                brand.setTextContent(productVoBrand);
            }

            //设置厂商名称
            String manuName = productUploadVo.getManufacturer();
            if (!StringUtils.isEmpty(manuName)) {
                Element manufacturer = document.createElement("Manufacturer");
                descriptionData.appendChild(manufacturer);
                manufacturer.setTextContent(manuName);
            }

            //设置厂商编号
            String manuNum = productUploadVo.getMfrPartNumber();
            if (!StringUtils.isEmpty(manuNum)) {
                Element mfrPartNumber = document.createElement("MfrPartNumber");
                descriptionData.appendChild(mfrPartNumber);
                mfrPartNumber.setTextContent(manuNum);
            }

            //设置要点
            String voBulletPoint = productUploadVo.getBulletPoint();
            if (!StringUtils.isEmpty(voBulletPoint)) {
                Element bulletPoint = document.createElement("BulletPoint");
                descriptionData.appendChild(bulletPoint);
                bulletPoint.setTextContent(voBulletPoint);
            }

            //设置描述
            String describe = productUploadVo.getDescription();
            if (!StringUtils.isEmpty(describe)) {
                Element description = document.createElement("Description");
                descriptionData.appendChild(description);
                description.setTextContent(describe);
            }

            //设置产品结点
            String recommendedBrowseNode1 = productUploadVo.getRecommendedBrowseNode();
            if (!StringUtils.isEmpty(recommendedBrowseNode1)) {
                Element recommendedBrowseNode = document.createElement("RecommendedBrowseNode");
                descriptionData.appendChild(recommendedBrowseNode);
                recommendedBrowseNode.setTextContent(recommendedBrowseNode1);
            }

            Element productData = document.createElement("ProductData");
            product.appendChild(productData);

//            //设置热门关键词
//            String keyword = productUploadVo.getSearchTerms();
//            if (!StringUtils.isEmpty(keyword)) {
//                Element searchTerms = document.createElement("SearchTerms");
//                productData.appendChild(searchTerms);
//                searchTerms.setTextContent(keyword);
//            }


            //设置产品分类
//            ProductTypeVo productTypeVo = productUploadVo.getProductTypeVo();
//            String type = "";
//            //获取产品分类
//            //获取产品一级分类
//            String productTypeOne = productTypeVo.getProductTypeOne();
//            //获取产品二级分类
//            String productTypeTwo = productTypeVo.getProductTypeTwo();
//            //获取产品三级分类
//            String productTypeThree = productTypeVo.getProductTypeThree();
//            //获取产品四级分类
//            String productTypeFour = productTypeVo.getProductTypeFour();
//            //获取产品五级分类
//            String productTypeFive = productTypeVo.getProductTypeFive();
//            //获取产品六级分类
//            String productTypeSix = productTypeVo.getProductTypeSix();
//            if (!StringUtils.isEmpty(productTypeOne)) {
//                type = productTypeOne;
//                if (!StringUtils.isEmpty(productTypeTwo)) {
//                    type = productTypeOne + "/" + productTypeTwo;
//                    if (!StringUtils.isEmpty(productTypeThree)) {
//                        type = productTypeOne + "/" + productTypeTwo + "/" + productTypeThree;
//                        if (!StringUtils.isEmpty(productTypeFour)) {
//                            type = productTypeOne + "/" + productTypeTwo
//                                    + "/" + productTypeThree + "/" + productTypeFour;
//                            if (!StringUtils.isEmpty(productTypeFive)) {
//                                type = productTypeOne + "/" + productTypeTwo
//                                        + "/" + productTypeThree + "/" + productTypeFour
//                                        + "/" + productTypeFive;
//                                if (!StringUtils.isEmpty(productTypeSix)) {
//                                    type = productTypeOne + "/" + productTypeTwo
//                                            + "/" + productTypeThree + "/" + productTypeFour
//                                            + "/" + productTypeFive + "/" + productTypeSix;
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            Element home = document.createElement("Home");
            productData.appendChild(home);

            Element productType = document.createElement("ProductType");
            home.appendChild(productType);

            Element home1 = document.createElement("Home");
            productType.appendChild(home1);


            Element parentage = document.createElement("Parentage");
            if(i >= 1){
                home.appendChild(parentage);
                parentage.setTextContent("child");
            }else {
                parentage.setTextContent("parent");
            }

            Element variationData = document.createElement("VariationData");
            home.appendChild(variationData);

            String variationTheme1 = productUploadVo.getVariationTheme();
            if (!StringUtils.isEmpty(variationTheme1)) {
                if(i >=1){
                    Element variationTheme = document.createElement("VariationTheme");
                    variationData.appendChild(variationTheme);
                    variationTheme.setTextContent(variationTheme1);

                    String color1 = productUploadVo.getColor();
                    if(!StringUtils.isEmpty(color1)){
                        Element color = document.createElement("Color");
                        variationData.appendChild(color);
                        color.setTextContent(color1);
                    }

                    String size1 = productUploadVo.getSize();
                    if(!StringUtils.isEmpty(size1)){
                        Element size = document.createElement("Size");
                        variationData.appendChild(size);
                        size.setTextContent(size1);
                    }
                }
            }

            String material1 = productUploadVo.getMaterial();
            if (!StringUtils.isEmpty(material1)) {
                Element material = document.createElement("Material");
                home.appendChild(material);
                material.setTextContent(material1);
            }

            String threadCount1 = productUploadVo.getThreadCount();
            if (!StringUtils.isEmpty(threadCount1)) {
                Element threadCount = document.createElement("ThreadCount");
                home.appendChild(threadCount);
                threadCount.setTextContent(threadCount1);
            }
            if(i >= 1){
                List<ProductUploadVo> vos = new ArrayList<>();
                ProductUploadVo remove = productVoList.remove(i - 1);
                vos.add(remove);
                createXML(vos);
                break;
            }
//            Element itemType = document.createElement("ItemType");
//            productData.appendChild(itemType);
//            itemType.setTextContent(type);
            if (i == (productVoList.size() - 1)) {
                try {
                    // 创建TransformerFactory对象
                    TransformerFactory tff = TransformerFactory.newInstance();
                    // 创建 Transformer对象
                    Transformer tf = tff.newTransformer();
                    // 输出内容是否使用换行
                    tf.setOutputProperty(OutputKeys.INDENT, "yes");
                    // 创建xml文件并写入内容
                    tf.transform(new DOMSource(document), new StreamResult(file));
                    return file;
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            }
            i++;
        }
        return file;
    }
}
